package com.example.HelloWorld;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "FirstServlet", value = "/first")
public class FirstServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //获得并处理与用户的请求，根据处理情况，决定响应的返回方式和用户跳转的下一个页面
        System.out.println("this is post method ");

        //request获取参数
        String username = request.getParameter("username");
        String pwd = request.getParameter("pwd");

        System.out.println("username:"+username);
        System.out.println("password:"+pwd);

        String msg = null;
        //判断用户名和密码不为空
        if(username!=null&&!"".equals(username)&&pwd!=null&&!"".equals(pwd)) {
            if (username.equals("lch") && pwd.equals("123")) {
                //登录成功,跳转到首页
                response.sendRedirect("index.jsp");//采用重定向方式跳转到jsp页面
                return;//成功的话防止底下那两行话运行request.setAttribute("msg",msg),request.getRequestDispatcher("login.jsp").forward(request,response);
            } else {
                //用户名或密码错误

                msg = "用户名或密码错误";
            }
        }else{
            //用户名密码不能为空

            msg = "用户名或密码不能为空";
            }


        //第一种返回方式(请求转发):带着错误提示信息，跳转回到登录页面
        request.setAttribute("msg",msg);//将错误提示信息放到request对象的属性当中
        request.getRequestDispatcher("login.jsp").forward(request,response);//请求转发


    }
}
